import { Platform, Linking } from 'react-native';
import Taro from '@tarojs/taro';
import { asyncTimeOut } from '../util';
import { lockAsync, OrientationLock } from 'expo-screen-orientation';
import { navigateTo } from '../router';

const createAsyncNoRepeat = () => {
  const callbacks = [];
  return {
    run: calback => {
      if (!callbacks.length) {
        calback()
          .then(() => {
            callbacks.forEach(v => v[0]());
            callbacks.splice(0);
          })
          .catch(err => {
            callbacks.forEach(v => v[1](err));
            callbacks.splice(0);
          });
      }
      return new Promise((resolve, reject) => {
        callbacks.push([resolve, reject]);
      });
    },
  };
};

/**
 * 验证ios端是否获得了网络请求权限
 * 因为ios app首次在手机上安装刚启动时请求会失败，需要做个验证，等待有网络之后再发起请求
 */
export const networkVerify = (() => {
  let status = false;
  const noRepeat = createAsyncNoRepeat();
  return async params => {
    if (Platform.OS === 'ios') {
      if (status) {
        return params;
      }
      await noRepeat.run(async () => {
        try {
          const res = await Taro.getStorage({ key: 'ios-request-verify' });
          if (res?.data) {
            status = true;
            return params;
          }
          throw '未获取本地信息';
        } catch (error) {
          // 去 递归验证
          const verify = async (level = 0) => {
            if (level > 120) {
              throw { message: '等待时间过长(超过30s) 请求失败' };
            }
            try {
              const baidu = await Taro.request({
                url: 'https://www.baidu.com',
              });
              if (baidu.statusCode !== 200) {
                throw '请求未成功';
              }
            } catch (error1) {
              if (error1?.statusCode !== 200) {
                await asyncTimeOut(200);
                await verify(level + 1);
              }
            }
          };
          await verify();
          await Taro.setStorage({ key: 'ios-request-verify', data: '1' });
        }
      });
      status = true;
      return params;
    } else {
      return params;
    }
  };
})();

/** 锁定屏幕方向-竖屏 */
export const screenOrientationLockAsyncVertical = () => {
  lockAsync(OrientationLock.PORTRAIT);
};

/** 锁定屏幕方向-横屏 */
export const screenOrientationLockAsyncHorizontal = () => {
  lockAsync(OrientationLock.LANDSCAPE);
};

/**
 * 预览文件
 * previewFile('https://501351981.github.io/vue-office/examples/dist/static/test-files/test.docx')
 * @param url
 */
export const previewFile = (url: string) => {
  if (!url || typeof url !== 'string') return;
  let lowerFileUrl = url.toLowerCase();
  let fileType = '';
  if (lowerFileUrl.includes('.docx')) {
    fileType = 'docx';
  } else if (lowerFileUrl.includes('.pdf')) {
    fileType = 'pdf';
  } else if (lowerFileUrl.includes('.xlsx')) {
    fileType = 'excel';
  } else if (strIncludeArray(lowerFileUrl, ['.png', '.jpg', '.jpeg', '.bmp', '.gif', '.webp', '.svg', '.tiff'])) {
    fileType = 'img';
  } else if (strIncludeArray(lowerFileUrl, ['.txt', '.json'])) {
    fileType = 'txt';
  }
  function strIncludeArray(str, array) {
    for (let i = 0; i < array.length; i++) {
      if (str.includes(array[i])) {
        return true;
      }
    }
    return false;
  }
  if (fileType === 'img') {
    Taro.previewImage({
      urls: [url],
      current: 0,
    });
  } else {
    if (['txt', 'img', 'excel', 'pdf', 'docx'].includes(fileType)) {
      navigateTo({
        url: '/pages/Webview/index',
        params: {
          title: '预览',
          url: `file:///android_asset/file-preview/index.html?fileUrl=${url}`,
        },
      });
    } else {
      console.log('openURL', url);
      Linking.openURL(url).catch(error => Taro.showToast({ title: JSON.stringify(error), icon: 'none' }));
    }
  }
};
